﻿using System.Reflection;
using TiaoTiaoCode.AutoUpdate.WebApi.Models;

namespace TiaoTiaoCode.AutoUpdate.WebApi.StartUps
{
    /// <summary>
    /// Api接口启动
    /// </summary>
    public static class ApiServicesStartup
    {
        /// <summary>
        /// Api接口IOC注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="config"></param>
        public static void AddApiServicesIOC(this IServiceCollection services, IConfiguration config)
        {
            var configItems = config.GetSection("ServicesIocConfig").Get<List<ServicesIocConfigModel>>();

            foreach (var cfg in configItems)
            {
                var asm = Assembly.Load(cfg.AssemblyName);
                var types = asm.GetTypes();

                foreach (var type in types)
                {
                    var ifs = type.GetInterfaces().Where(t => t.Namespace == cfg.InterfaceBaseNamespace);
                    if (ifs.Count() <= 0) continue;
                    if (!ifs.Any(t => t.Name.StartsWith("I") && t.Name.EndsWith("Service"))) continue;

                    var inter = ifs.First(t => t.Name.StartsWith("I") && t.Name.EndsWith("Service"));

                    services.AddScoped(inter, type);
                }
            }
        }
    }
}
